import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
const request = axios.create({
  // 从vue.config.js中的服务器反向代理中获取基地址,拼接上/api
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

request.interceptors.request.use((config) => {
  // 从store中的getters模块中获取token
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})
// 响应拦截器
request.interceptors.response.use((response) => {
  // 如果是返回的是文件类型
  if (response.data instanceof Blob) {
    return response.data
  }
  const { data, message, success } = response.data // 剥离一层data
  if (success) {
    return data // 再剥离一层
  } else {
    Message({ type: 'error', message })
    return Promise.reject(new Error(message))
  }
}, async(error) => {
  // 401
  if (error.response.status === 401) {
    store.dispatch('user/logoutActions')
    Message.warning('登录过期,请重新登录')
    return Promise.reject(error)
  }

  Message({ type: 'error', message: error.message })
  return Promise.reject(error)
})

export default request
